package cosw.com.shanghaica;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.cosw.sdkShanghaiCA.BleScanCallback;
import com.cosw.sdkShanghaiCA.BleStateListener;
import com.cosw.sdkShanghaiCA.SHCAProvider;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements View.OnClickListener, BleScanCallback,
    BleStateListener {

  public static final String EMPTY = "EMPTY";

  private SHCAProvider provider;
  private ImageView imageview_scan;

  private ArrayAdapter deviceAdapter;
  ArrayList<String> deviceNames;
  public static BluetoothDevice device;
  ArrayList<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();
  private int selectIndex = -1;

  private Context mContext;

  private SharedPreferences prefs;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mContext = this;

    provider = SHCAProvider.getInstance(this.getApplication());
    provider.setListener(this);

    deviceNames = new ArrayList<String>();
    deviceAdapter = new ArrayAdapter<String>(this,
        R.layout.list_item_ble_device, deviceNames);

    findView();

    prefs = PreferenceManager
        .getDefaultSharedPreferences(this.getApplication());
  }

  private void findView() {
    imageview_scan = (ImageView) this.findViewById(R.id.imageview_scan);
    imageview_scan.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.imageview_scan:
        startScanning();
        break;
    }
  }

  private void startScanning() {
    deviceNames.clear();
    devices.clear();
    selectIndex = -1;

    provider.scanDevice(5000, this);

    LinearLayout linearLayoutMain = new LinearLayout(this);// 自定义一个布局文件
    linearLayoutMain.setLayoutParams(new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
    ListView listView = new ListView(this);// this为获取当前的上下文
    listView.setFadingEdgeLength(0);
    listView.setAdapter(deviceAdapter);

    linearLayoutMain.addView(listView);// 往这个布局中加入listview
    final AlertDialog dialog = new AlertDialog.Builder(this)
        .setTitle("设备列表").setView(linearLayoutMain)// 在这里把写好的这个listview的布局加载dialog中
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {

          @Override
          public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            dialog.cancel();
            provider.stopLeScan();
          }
        }).create();
    dialog.setCanceledOnTouchOutside(false);// 使除了dialog以外的地方不能被点击
    dialog.show();
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {// 响应listview中的item的点击事件
      @Override
      public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
          long arg3) {
        dialog.cancel();

        selectIndex = pos;
        device = devices.get(pos);
        //devices.get(pos).setScanRecord(StringUtil.hexStringToByteArray(DEFAULT_SCAN_RECORD));
        provider.connectDevice(device.getName(), "778899", 10000, MainActivity.this);
      }
    });
  }

  @Override
  public void onScannedWithDevice(final BluetoothDevice scannedDevice) {
    MainActivity.this.runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Log.e("onScannedWithDevice", scannedDevice
            .getName()
            + " "
            + scannedDevice.getAddress());

        String name = scannedDevice.getName();
        if (name == null || name.equals("")) {
          name = scannedDevice.getAddress()
              .replace(":", "");
        }

        deviceNames.add(name);
        devices.add(scannedDevice);
        deviceAdapter.notifyDataSetChanged();
      }
    });
  }

  @Override
  public void onScannedFinish(List<BluetoothDevice> scannedDevices) {
// TODO Auto-generated method stub
    if (scannedDevices.size() == 0) {
      Toast.makeText(mContext, "很报歉，未收到附近的BLE设备！", Toast.LENGTH_LONG)
          .show();
    }
  }

  @Override
  public void onScannedFailed(String msg) {
    Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
  }

  @Override
  public void onConnectSuccess() {
    Toast.makeText(mContext, "连接成功", Toast.LENGTH_LONG).show();
    String superPin = prefs.getString("superPin", EMPTY);
    String adminPin = prefs.getString("adminPin", EMPTY);
    if (EMPTY.equals(superPin) || EMPTY.equals(adminPin)) {
      Intent intent = new Intent(MainActivity.this, InitDeviceActivity.class);
      startActivity(intent);
      finish();
    } else {
      Intent intent = new Intent(MainActivity.this, DeviceManageActivity.class);
      startActivity(intent);
      finish();
    }
  }

  @Override
  public void onConnectFailed(String msg) {
    Toast.makeText(mContext, "连接失败", Toast.LENGTH_LONG).show();
  }

  @Override
  public void onConnectingLost() {
    Toast.makeText(mContext, "连接已断开", Toast.LENGTH_LONG).show();
  }
}
